package com.yf.openapi.modules.token.controller;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.yf.ability.BaseConfig;
import com.yf.ability.redis.service.RedisService;
import com.yf.ability.shiro.jwt.JwtUtils;
import com.yf.base.api.api.ApiRest;
import com.yf.base.api.api.controller.BaseController;
import com.yf.base.api.exception.ServiceException;
import com.yf.base.utils.DateUtils;
import com.yf.openapi.modules.token.dto.request.TokenReqDTO;
import com.yf.openapi.modules.token.dto.response.TokenRespDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Api(tags = {"授权接口"})
public class TokenController extends BaseController {

    @Autowired
    private RedisService redisService;

    @Autowired
    private BaseConfig baseConfig;

    /**
     * 查找考试记录
     * @param reqDTO
     * @return
     */
    @ApiOperation(value = "获取授权Access")
    @PostMapping("/api/open/access")
    public ApiRest<TokenRespDTO> token(@RequestBody TokenReqDTO reqDTO) {

        // 对比系统秘钥
        if(!baseConfig.getOpenSecret().equals(reqDTO.getSecret())){
            throw new ServiceException("授权秘钥错误！");
        }

        // 随机生成
        String access = JwtUtils.sign(IdWorker.getIdStr());

        // 存入redis
        redisService.set(access, DateUtils.dateNow("yyyy-MM-dd HH:mm:ss"), reqDTO.getExpires());

        // 响应
        TokenRespDTO respDTO = new TokenRespDTO();
        respDTO.setAccess(access);
        return success(respDTO);
    }

}
